package com.zyt.controller;

import com.zyt.entity.*;
import com.zyt.service.*;
import com.zyt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired

    private OrderItemService orderItemService;
    @RequestMapping("/insertOrder")
    public String insertOrder(int addressId, HttpSession session){
        User user =(User) session.getAttribute("user");
        Cart cart = (Cart)session.getAttribute("cart");
        Order order=new Order();
        order.setUser(user);
        Address address=new Address();
        address.setAid(addressId);
        order.setAddress(address);

        order.setOrderState(1);

        order.setGoodPrice(cart.getTotalMoney());
        orderService.insertOrder(order);


        Map<Integer, CarItem> buMap = cart.getBuyMap();
        Set<Map.Entry<Integer,CarItem>> entries = buMap.entrySet();
        for (Map.Entry<Integer,CarItem> entry:entries){
            OrderItem orderItem = new OrderItem();
            CarItem value= entry.getValue();
            Book book= value.getBook();

            orderItem.setBook(book);

            orderItem.setOrder(order);
            orderItem.setCount(value.getCount());

            orderItem.setAmount(value.getCount()*value.getBook().getDangprice());

            orderItemService.insertOrderItem(orderItem);

        }
        return "/order/order_ok.jsp";
    }
    @RequestMapping("/selectByUserId")
    public String selectByUserId(HttpSession session, Model model){
        User user =(User) session.getAttribute("user");
        List<Order> orderList =orderService.selectByUserId(user.getId());
        model.addAttribute("orders",orderList);
        return "/order/my_order.jsp";
    }
}
